package com.cyd.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.cyd.base.APPBASE;

public class CityDataBase {
	private String packName = "com.cyd.homefamily";
	private String dbName = "chinacity.db";
	private String dbPath = APPBASE.getExternalDir() + File.separator
			+ packName + File.separator + dbName;
	private SQLiteDatabase database;
	private File file;
	private Context context;

	public SQLiteDatabase getDatabase() {
		return database;
	}

	public CityDataBase(Context context) {
		this.context = context;
		file = new File(APPBASE.getExternalDir() + File.separator + packName);
		if (!file.exists())
			file.mkdir();
		database = copyDatabase();
	}

	private SQLiteDatabase copyDatabase() {
		file = new File(dbPath);
		InputStream is = null;
		FileOutputStream fos = null;
		if (!file.exists()) {
			try {
				is = context.getResources().getAssets().open("chinacity.db");
				fos = new FileOutputStream(file.getPath());
				byte[] buffer = new byte[1024];
				int count = 0;
				while ((count = is.read(buffer)) != -1) {
					fos.write(buffer, 0, count);
					fos.flush();
				}
				database = SQLiteDatabase.openDatabase(file.getPath(), null,
						SQLiteDatabase.CREATE_IF_NECESSARY);
				is.close();
				fos.close();
				LogMsg.i("success");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		} else {
			database = SQLiteDatabase
					.openOrCreateDatabase(file.getPath(), null);
		}
		return database;
	}

	public String[] getPCC(String sql, String column) {
		Cursor cursor = database.rawQuery(sql, null);
		cursor.moveToFirst();
		String[] PCC = new String[cursor.getCount()];
		for (int i = 0; i < cursor.getCount(); i++) {
			String str = cursor.getString(cursor.getColumnIndex(column));
			if (str != null)
				PCC[i] = str;
			cursor.moveToNext();
		}
		return PCC;
	}
}
